var util = require('../../comm/script/util.js')
const app = getApp();
const { SERVER_URL } = require('../../comm/script/config.js');

Page({
	data: {
		films: [],
		hasMore: true,
		showLoading: true,
		start: 0,
		count: 20, // 每次加载的数量
		windowHeight: 0
	},

	onLoad: function() {
		var that = this;
		that.loadFilms();
	},

	onShow: function() {
		var that = this
		try {
			const windowInfo = wx.getWindowInfo();
			if (windowInfo && typeof windowInfo.windowHeight === 'number') {
				that.setData({
					windowHeight: windowInfo.windowHeight
				})
			} else {
				console.warn('wx.getWindowInfo() 返回无效的 windowHeight，使用默认值。');
				that.setData({
					windowHeight: 500 // 设置一个默认值
				})
			}
		} catch (error) {
			console.error('获取窗口信息失败:', error)
			that.setData({
				windowHeight: 500 // 设置一个默认值
			})
		}
	},

	loadFilms: function() {
		var that = this;
		if (!that.data.hasMore) {
			return;
		}

		that.setData({ showLoading: true });

		wx.request({
			url: `${SERVER_URL}/api/movies`,
			method: 'GET',
			data: {
				start: that.data.start,
				count: that.data.count
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const rawFilms = res.data;
					console.log('popular.js - API 响应完整内容:', res.data);
					const newFilms = rawFilms.map(item => {
						// 统一图片字段获取逻辑
						const imageUrl = item.imageUrl || item.image_url || (item.images && item.images.large) || '';
						item.images = { large: imageUrl || 'https://example.com/default-image.jpg' };
						item.directors = item.director ? [{ name: item.director, id: item.director_id || null }] : [];
						item.casts = String(item.cast || '').split(',').map(name => ({ name: name.trim(), id: null }));
						item.genres = Array.isArray(item.genres) ? item.genres.map(genre => genre.trim()) : (item.genres ? item.genres.split(',').map(genre => genre.trim()) : []);
						item.rating = {
							average: parseFloat(item.average_rating || item.averageRating) || 0,
							stars: ((parseFloat(item.average_rating || item.averageRating) / 2) * 5).toFixed(0)
						};
						item.year = item.release_date
						  ? (item.release_date instanceof Date
							? item.release_date.getFullYear().toString()
							: String(item.release_date).split('-')[0])
						  : '';
						return item;
					});

					console.log('popular.js - 格式化后的 newFilms:', newFilms);

					if (newFilms.length > 0) {
						// 合并后去重（按id）
						const allFilms = that.data.films.concat(newFilms);
						const uniqueFilms = [];
						const filmIds = new Set();
						for (const film of allFilms) {
							if (film.id && !filmIds.has(film.id)) {
								uniqueFilms.push(film);
								filmIds.add(film.id);
							}
						}
						that.setData({
							films: uniqueFilms,
							start: uniqueFilms.length,
							hasMore: newFilms.length === that.data.count,
							showLoading: false
						});
					} else {
						that.setData({
							hasMore: false,
							showLoading: false
						});
					}
				} else {
					wx.showToast({
						title: res.data.message || '加载电影失败',
						icon: 'none'
					});
					that.setData({ showLoading: false });
				}
			},
			fail: (error) => {
				console.error('加载电影失败:', error);
				wx.showToast({
					title: '加载电影失败，请检查网络或服务器',
					icon: 'none'
				});
				that.setData({ showLoading: false });
			}
		});
	},

	scroll: function(e) {
		console.log(e);
	},

	scrolltolower: function() {},

	onPullDownRefresh: function() {
		var that = this;
		that.setData({
			films: [],
			hasMore: true,
			showLoading: true,
			start: 0
		});
		that.loadFilms();
		wx.stopPullDownRefresh(); // 停止下拉刷新动画
	},

	viewFilmDetail: function(e) {
		var id = e.detail.id;
		console.log('当前登录状态：', util.checkLoginStatus());
		if (!util.checkLoginStatus()) {
			console.log('检测到未登录，正在强制跳转到登录页面...');
			util.setRedirectFilmId(id);
			wx.reLaunch({
				url: "../login/login?filmId=" + id
			});
			return;
		}
		wx.navigateTo({
			url: "../filmDetail/filmDetail?id=" + id
		});
	},

	viewFilmByTag: function(e) {
		var data = e.currentTarget.dataset;
		var keyword = data.tag;
		wx.navigateTo({
			url: '../searchResult/searchResult?url=' + encodeURIComponent(`${SERVER_URL}/api/search?tag=`) + keyword + '&keyword=' + keyword
		});
	}
});